package com.astrob.activitys;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.astrob.NavFrameSDK.POIDescription;
import com.astrob.adapters.PlanFuncAdapter;
import com.astrob.adapters.PlanFuncAdapter.PlanFuncItem;
import com.astrob.adapters.PlanFuncAdapter.PlanFuncListener;
import com.astrob.adapters.PlanHistoryAdapter;
import com.astrob.adapters.PlanHistoryAdapter.HistoryItemListener;
import com.astrob.adapters.SearchAroundItemAdapter;
import com.astrob.adapters.SearchAroundItemAdapter.POIDesc;
import com.astrob.model.FavoriteFileHandle;
import com.astrob.model.HistoryData;
import com.astrob.model.HistoryFileHandle;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.model.RoutePlanDataHandle;
import com.astrob.model.SearchParm;
import com.astrob.model.SystemSetFileHandle;
import com.astrob.naviframe.Start;
import com.astrob.util.Utils;
import com.astrob.nhcmap.R;


import java.util.ArrayList;
import java.util.List;

public class AddRoutePointActivity extends Activity {
	public static int SET_START = 1;
	public static int SET_DEST = 2;
	public static int ADD_DEST = 3;
	ListView mListFunc;
	ListView mListHistory;
	PlanFuncAdapter mFuncAdapter;
	PlanHistoryAdapter mHistoryAdapter;
	ArrayList<PlanFuncItem> mItems;
	
	ListView mListSearch;
	SearchAroundItemAdapter mSearchAdapter;
	
	private Button mBtsearchkey;
	private Button mBtclearkey;
	private AutoCompleteTextView mInput;
	
	private int mMode = ADD_DEST;
	private int mPos = -1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addroutepoint);
		mInput = (AutoCompleteTextView) findViewById(R.id.search_input);

		Bundle bundle = getIntent().getExtras();
		if(bundle != null){
			mMode = bundle.getInt("mode");
			mPos = bundle.getInt("pos", 0);
			String preName = bundle.getString("preName");
			if(preName != null){
				mInput.setText(preName);
			}
		}
		TextView title = (TextView)findViewById(R.id.title);
		if(mMode == SET_START){
			title.setText("设置起点");
		} else if(mMode == SET_DEST){
			title.setText("修改目的地");
		} else{
			title.setText("添加目的地");
		}
		
		mListFunc = (ListView)findViewById(R.id.listview_func);
		mListHistory = (ListView)findViewById(R.id.listview_history);
		mListSearch = (ListView)findViewById(R.id.listview_searchresult);
		
		mItems = new ArrayList<PlanFuncAdapter.PlanFuncItem>();
		addItem(R.drawable.icon_mylocation, "我的位置");
		addItem(R.drawable.icon_maplocation, "地图选点");
		addItem(R.drawable.icon_nearlocation, "周边选点");
		addItem(R.drawable.icon_favlocation, "收藏选点");
		mFuncAdapter = new PlanFuncAdapter(this, mItems);
		mFuncAdapter.setListener(new PlanFuncListener() {
			@Override
			public void onFunc(int pos) {
				if(pos == 0){
					onMyLocation();
				} else if(pos == 1){
					onMap();
				} else if(pos == 2){
					onNear();
				} else if(pos == 3){
					onFav();
				}
			}
		});
		mListFunc.setAdapter(mFuncAdapter);
		
		mHistoryAdapter = new PlanHistoryAdapter(this);
		mHistoryAdapter.setListener(new HistoryItemListener() {
			
			@Override
			public void onEmpty() {
				alertClearHistory();
			}
			
			@Override
			public void onDelFav(HistoryData data) {
				FavoriteFileHandle.getInstance().deleteByHist(data);
				mHistoryAdapter.notifyDataSetChanged();
			}
			
			@Override
			public void onAddFav(HistoryData data) {
				FavoriteFileHandle.getInstance().addByHist(data);
				mHistoryAdapter.notifyDataSetChanged();				
			}

			@Override
			public void onItem(HistoryData data) {
				doAddRoutePoint(data);
				setResult(Msg.CHANGE_ROUTEMGR);
				finish();
			}
		});
		mListHistory.setAdapter(mHistoryAdapter);
		
		mSearchAdapter = new SearchAroundItemAdapter(this);
		mListSearch.setAdapter(mSearchAdapter);
		mListSearch.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
				onSearchResultItem(position);
			}
		});
		
		mBtsearchkey = (Button) findViewById(R.id.searchkey_btn);
		mBtsearchkey.setVisibility(View.GONE);
		mBtclearkey = (Button) findViewById(R.id.clearkey_btn);
		mBtclearkey.setVisibility(View.GONE);
		final View activityRootView = findViewById(R.id.addroutepoint_layout);
		activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {
					private int preHeight = 0;

					@Override
					public void onGlobalLayout() {
						int heightDiff = activityRootView.getRootView()
								.getHeight() - activityRootView.getHeight();
						System.out.println("height differ = " + heightDiff);
						// 在数据相同时，减少发送重复消息。因为实际上在输入法出现时会多次调用这个onGlobalLayout方法。
						if (preHeight == heightDiff) {
							return;
						}
						preHeight = heightDiff;
						if (heightDiff > 100) {
//							mBtsearchkey.setVisibility(View.GONE);
							mBtsearchkey.setVisibility(View.VISIBLE);
							mBtclearkey.setVisibility(View.VISIBLE);
						} else {
							mBtsearchkey.setVisibility(View.GONE);
							mBtclearkey.setVisibility(View.GONE);
						}
					}

				});
		
		mInput.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId,
										  KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_NEXT
						|| actionId == EditorInfo.IME_ACTION_DONE
						|| actionId == EditorInfo.IME_ACTION_GO
						|| actionId == EditorInfo.IME_ACTION_SEARCH) {
					//onKeyWordChange();
					//Toast.makeText(getApplicationContext(), "开始查询", Toast.LENGTH_SHORT).show();
					startQuery();
				}
				return false;
			}
		});
	}
	protected void alertClearHistory() {
		if(HistoryFileHandle.getInstance().getNativeHistory().size() <= 0){
			return;
		}
		new AlertDialog.Builder(this)
		.setTitle(getString(R.string.dlg_title))
		.setMessage("您确认清空所有历史记录吗？")
		.setPositiveButton(getString(R.string.yes),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						//确认清除数据
						HistoryFileHandle.getInstance().clearNativeHistory();
						mHistoryAdapter.notifyDataSetChanged();
					}
				})
		.setNegativeButton(getString(R.string.cancel), null).show();
	}
	private void doAddRoutePoint(HistoryData data){
		if(mMode == ADD_DEST){
			RoutePlanDataHandle.getInstance().addDest(data);
		} else if(mMode == SET_DEST){
			RoutePlanDataHandle.getInstance().changeDest(data, mPos);
		} else{
			RoutePlanDataHandle.getInstance().setStart(data);
		}
	}
	protected void onSearchResultItem(int pos) {
		if (Utils.isFastDoubleClick())
			return;
		if (pos < 0 || pos >= Start.getInstance().MapKit().mPOIResult.size())
			return;
		
		HistoryData data = new HistoryData();
		
		double lon = Start.getInstance().MapKit().mPOIResult.get(pos).position.lon;
		double lat = Start.getInstance().MapKit().mPOIResult.get(pos).position.lat;
		String name = Start.getInstance().MapKit().mPOIResult.get(pos).name;
		data.setLl(new LonLat(lon, lat));
		data.setName(name);
		doAddRoutePoint(data);
		setResult(Msg.CHANGE_ROUTEMGR);
		finish();
	}
	public static void launch(final Activity context, final int mode){
		Intent intent = new Intent(context, AddRoutePointActivity.class);
		intent.putExtra("mode", mode);
		context.startActivityForResult(intent, 3);
	}
	public static void launchChangeDest(final Activity context, final int mode, final int pos, final String name){
		Intent intent = new Intent(context, AddRoutePointActivity.class);
		intent.putExtra("mode", mode);
		intent.putExtra("pos", pos);
		intent.putExtra("preName", name);
		context.startActivityForResult(intent, 3);
	}

	protected void onFav() {
		if (Utils.isFastDoubleClick())
			return;
		
		Intent intent = new Intent(this, NewFavActivity.class);
		intent.putExtra("TypeFlag", mMode);  //跟原先代码兼容
		intent.putExtra("DestIndex", mPos);
		startActivityForResult(intent, 3);
	}
	protected void onNear() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, SearchAroundActivity.class);
		intent.putExtra("mode", mMode);
		intent.putExtra("pos", mPos);
		startActivityForResult(intent, 3);
	}
	protected void onMap() {
		// TODO Auto-generated method stub
		if (Utils.isFastDoubleClick())
			return;
		Intent intent = new Intent(this, NaviActivity.class);
		intent.putExtra("TypeFlag", mMode);  //跟原先代码兼容
		intent.putExtra("DestIndex", mPos);
		intent.putExtra("showOnmap", true);
		intent.putExtra("mapcenterlon", Start.getInstance().MapKit().getMapCenter().GetLon());
		intent.putExtra("mapcenterlat", Start.getInstance().MapKit().getMapCenter().GetLat());
		startActivityForResult(intent, Msg.REQUEST_SHOW_ON_MAP);
	}
	protected void onMyLocation() {
		// TODO Auto-generated method stub
		if (Utils.isFastDoubleClick())
			return;
		HistoryData data = new HistoryData();
		double dlon = SystemSetFileHandle.getInstance().getSystemSet().previewLon;
		double dlat = SystemSetFileHandle.getInstance().getSystemSet().previewLat;
		data.setLl(new LonLat(dlon, dlat));
		data.setName(getString(R.string.the_current_position));
		doAddRoutePoint(data);
		//
		setResult(Msg.CHANGE_ROUTEMGR);
		finish();
	}
	private void addItem(int id, String text){
		PlanFuncItem item = new PlanFuncItem();
		item.imgId = id;
		item.text = text;
		mItems.add(item);
	}
	public void onBack(View v){
		if(mListSearch.getVisibility() == View.GONE){
			//为了同步清除历史目的地的刷新，每次返回都要刷新页面
			setResult(Msg.CHANGE_ROUTEMGR);
			finish();
		} else {
			backFromInputMode();
		}
	}
	@Override
	public void onBackPressed() {
		onBack(null);
//		super.onBackPressed();
	}
	public void backFromInputMode(){
		mListSearch.setVisibility(View.GONE);
		mListFunc.setVisibility(View.VISIBLE);
		mListHistory.setVisibility(View.VISIBLE);
		mInput.setText("");
		InputMethodManager m = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		m.hideSoftInputFromWindow(mInput.getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}
	
	public void onClearkey(View v){
		mInput.setText("");
	}
	public void onSearch(View v){
		String key = mInput.getText().toString();
		if(key.length() == 0){
			alertErr("您未输入查询关键词!");
			return;
		}
		startQuery();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(Msg.CHANGE_ROUTEMGR == resultCode){
			setResult(Msg.CHANGE_ROUTEMGR);
			finish();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	protected void startQuery() {
		mListSearch.setVisibility(View.VISIBLE);
		mListFunc.setVisibility(View.GONE);
		mListHistory.setVisibility(View.GONE);
		new DoQueryTask().execute((Void)null);
	}
	void alertErr(String err){
		Toast.makeText(this, err, Toast.LENGTH_SHORT).show();
	}
	ProgressDialog mPB;
	public class DoQueryTask extends AsyncTask<Void, Integer, Boolean> {

		String keyword = "";
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (mPB != null) {
				mPB.cancel();
				mPB = null;
			}
			mPB = ProgressDialog.show(AddRoutePointActivity.this, "正在查询", "查询中...");
			keyword = mInput.getText().toString();
		}

		@Override
		protected Boolean doInBackground(Void... param) {
			SearchParm sp = new SearchParm();
			sp.dLon = Start.getInstance().MapKit().mCityPosition.lon;
			sp.dLat = Start.getInstance().MapKit().mCityPosition.lat;
			sp.poiType = "All POI";
			sp.range = 100000;
			sp.keyword = keyword;
			Start.getInstance().MapKit().mSearchParm = sp;
			int ret = Start.getInstance().MapKit().nearQuery(false);
			if(ret < 0){
				return false;
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (mPB != null) {
				mPB.cancel();
				mPB = null;
			}
			InputMethodManager m = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			m.hideSoftInputFromWindow(mInput.getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
			
			List<POIDesc> poiList = new ArrayList<POIDesc>();
			LonLat center = Start.getInstance().MapKit().getMapCenter();
			for (int i = 0; i < Start.getInstance().MapKit().mPOIResult.size(); i++) {
				POIDesc item = new POIDesc();
				POIDescription poidata = Start.getInstance().MapKit().mPOIResult.get(i);
				item.name = poidata.name;
				LonLat poill = new LonLat(poidata.position.lon,
						poidata.position.lat);
				item.direct = Start.getInstance().MapKit().getDirection(center, poill);
				item.distance = Start.getInstance().MapKit().getDistanceString(poidata.rank);
				item.index = i;
				if (poidata.address != null) {
					item.addr = poidata.address;
				}
				if (poidata.tel != null) {
					item.phone = poidata.tel;
				}
				poiList.add(item);
			}

			mSearchAdapter.setDataList(poiList);
			mSearchAdapter.notifyDataSetChanged();

			if (Start.getInstance().MapKit().mPOIResult.size() <= 0) {
				alertErr("查询无结果");
			}
			//listView.setSelection(0);
			super.onPostExecute(result);
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
}
